<template>
    <div>
        <div class="px-4 my-4 mb-8">
            <el-page-header :icon="ArrowLeft" @back="router.back()">
                <template #breadcrumb>
                    <el-breadcrumb separator="/">
                        <el-breadcrumb-item>知识库管理</el-breadcrumb-item>
                        <el-breadcrumb-item>{{
                            currentKbInfo.title
                        }}</el-breadcrumb-item>
                        <el-breadcrumb-item>上传文件</el-breadcrumb-item>
                    </el-breadcrumb>
                </template>
                <template #content>
                    <span class="text-2xl font-600">
                        {{ '上传文件' }}
                    </span>
                </template>
            </el-page-header>
        </div>
        <!-- <div class="m-4 text-2xl">知识库文件管理</div> -->
        <div class="m-4">
            <div class="mt-12">
                <el-steps
                    :active="currentStep"
                    align-center
                    finish-status="success"
                    :process-status="'finish'"
                    simple
                >
                    <el-step title="上传文件" description="上传文件" />
                    <el-step title="向量化" description="向量化" />
                    <el-step
                        v-if="currentStep !== 3"
                        :status="currentStep === 2 ? 'success' : 'wait'"
                        title="完成"
                        description="完成"
                    />
                    <el-step
                        v-if="currentStep === 3"
                        status="error"
                        title="失败"
                        description="失败"
                    />
                </el-steps>
            </div>

            <div v-if="currentStep === 0">
                <div class="mt-12 flex items-center">
                    <div>文件类型：</div>
                    <div class="flex">
                        <div
                            v-for="item in fileTypes"
                            class="flex justify-center items-center mr-8 border-2 p-4 rounded-xl cursor-pointer hover:border-blue-300"
                            :class="{
                                'border-blue-300': item.value === form.type,
                                'bg-light-300': item.value === form.type,
                            }"
                            @click="form.type = item.value"
                        >
                            <el-image
                                :src="icons[item.value]"
                                class="w-[50px] mr-4"
                            />
                            <div>
                                <div>{{ item.label }}</div>
                                <div class="text-gray-400 whitespace-nowrap">
                                    {{ item.desc }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="mt-12 flex items-center">
                    <div>上传文件：</div>
                    <div class="flex">
                        <el-upload
                            class="w-[500px]"
                            drag
                            :auto-upload="false"
                            ref="uploadRef"
                            :limit="1"
                            :accept="
                                fileTypes.find((v) => v.value === form.type)
                                    ?.accept
                            "
                            @change="uploadChange"
                            @remove="uploadFile = null"
                        >
                            <el-icon class="el-icon--upload">
                                <UploadFilled />
                            </el-icon>
                            <div class="el-upload__text">
                                拖拽文件或 <em>点击此处</em> 上传文件
                            </div>
                            <template #tip>
                                <!-- <div class="el-upload__tip">
                                jpg/png files with a size less than 500kb
                            </div> -->
                            </template>
                        </el-upload>
                    </div>
                </div>
                <div class="mt-12 flex justify-center w-full">
                    <el-button type="primary" @click="uploadNext" size="large"
                        >下一步</el-button
                    >
                </div>
            </div>

            <div
                class="flex flex-col items-center w-full"
                v-if="currentStep === 1"
            >
                <div class="h-[150px] mt-[200px]">
                    <LoadAnim />
                </div>
                <div class="text-3xl text-[#cccccc]">正在向量化. . .</div>
            </div>
            <div
                class="flex flex-col items-center w-full"
                v-if="currentStep === 2"
            >
                <div class="h-[150px] mt-[200px]">
                    <el-icon :size="100" color="#67c23a">
                        <CircleCheck />
                    </el-icon>
                </div>
                <div class="text-3xl text-[#cccccc]">完成</div>
                <el-button class="mt-8" @click="router.back()">返回</el-button>
            </div>
            <div
                class="flex flex-col items-center w-full"
                v-if="currentStep === 3"
            >
                <div class="h-[150px] mt-[200px]">
                    <el-icon :size="100" color="#f56c6c">
                        <CircleClose />
                    </el-icon>
                </div>
                <div class="text-3xl text-[#cccccc]">向量化失败</div>
                <el-button class="mt-8" @click="router.back()">返回</el-button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { getList } from '@/apis/commonCrud'
import { uploadKnowledgeBase } from '@/apis/upload'
import icons from '@/assets/fileType/index'
import {
    ArrowLeft,
    UploadFilled,
    CircleCheck,
    CircleClose,
} from '@element-plus/icons-vue'
import { ElMessage, UploadFile, UploadInstance } from 'element-plus'
import { onBeforeMount, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import LoadAnim from './LoadAnim.vue'

const router = useRouter()
const route = useRoute()

const fileTypes = [
    {
        label: 'MARKDOWN',
        value: 'md',
        desc: '上传markdown文件',
        accept: '.md',
    },
    {
        label: 'TXT',
        value: 'txt',
        desc: '上传txt文件',
        accept: '.txt',
    },
    {
        label: 'PDF',
        value: 'pdf',
        desc: '上传PDF文件',
        accept: '.pdf',
        // accept: 'application/pdf',
    },
    {
        label: 'WORD',
        value: 'docx',
        desc: '上传WORD文件',
        accept: '.doc,.docx',
        // accept: 'application/pdf',
    },
    // {
    //     label: 'PPT',
    //     value: 'pptx',
    //     desc: '上传.ppt，.pptx文件'
    // },
]

const form = reactive({
    filename: '',
    type: 'md',
})
const uploadRef = ref<UploadInstance>()
const currentKbInfo = ref<any>({})
const currentStep = ref(0)
let uploadFile: File | null = null

const getCurrentKbInfo = async () => {
    const knowledgeBaseId = route.params.id
    if (!knowledgeBaseId) return
    const res = await getList('knowledgeBases', {
        id: knowledgeBaseId,
    })
    if (!res.success) {
        ElMessage.error('获取数据失败')
        return
    }
    currentKbInfo.value = res.data.rows[0]
}

getCurrentKbInfo()

const uploadChange = (file: UploadFile) => {
    if (!file.raw) return
    uploadFile = file.raw
}

// 轮询文件状态
let timer: number | null = null
const getFileStatus = async (id: number) => {
    const res = await getList('knowledgeBaseFiles', {
        id,
        attributes: {
            includes: ['status'],
        },
    })
    const status = res.data.rows[0].status
    const statusMap = {
        Embedding: 1,
        Embedded: 2,
        Failed: 3,
    }
    currentStep.value = statusMap[status]
    if (currentStep.value > 1) return
    if (!timer) return
    timer = setTimeout(() => {
        getFileStatus(id)
    }, 1000)
}

onBeforeMount(() => {
    if (timer !== null) {
        clearTimeout(timer)
        timer = null
    }
})

const uploadNext = async () => {
    console.log(uploadRef.value)
    if (!uploadFile) {
        ElMessage.error('请选择文件')
        return
    }
    const { type } = form
    const { id, collectionName } = currentKbInfo.value
    if (!type || !id || !collectionName) {
        ElMessage.error('请选择知识库')
        return
    }
    const res = await uploadKnowledgeBase([uploadFile], {
        knowledgeBaseId: id,
        collectionName: collectionName,
        type,
    })

    if (!res.success) {
        ElMessage.error('上传失败')
        return
    }
    timer = setTimeout(() => {
        getFileStatus(res.data.id)
    }, 1000)
    ElMessage.success('上传成功')
}
</script>

<style scoped></style>
